import { defineStore } from 'pinia'
import type { LoginData, UserLoginResponseData, UserInfo } from '@/api/hospital/type'
// 引入验证码获取接口
import { reqCode, reqUserLogin } from '@/api/hospital/index'
import { SET_USERINFO, REMOVE_USERINFO, GET_USERINFO } from '@/utils/user'
import { ref } from 'vue'
import { setInterval } from 'timers/promises'

// 选取组合式api构建分支仓库

// 定义用户相关的仓库
export const useUserStore = defineStore('user', () => {
    //actions 显示登录框
    const showLogin = () => {
        visible.value = true
    }

    //actions 隐藏登录框
    const closeLogin = () => {
        visible.value = false
    }

    //actions 获取验证码方法
    const getCode = async (phone: string) => {
        const res = await reqCode(phone)
        if (res.code === 200)
            code.value = res.data ? res.data : code.value
        else {
            return Promise.reject(new Error(res.message))
        }
    }

    //actions 用户通过手机号码发起登录请求
    const userLogin = async (loginData: LoginData) => {
        const res: UserLoginResponseData = await reqUserLogin(loginData)
        if (res.code === 200) {
            userInfo.value = res.data
            // 本地持久化存储用户信息
            SET_USERINFO(JSON.stringify(userInfo.value))
            return 'ok'
        } else {
            return Promise.reject(new Error(res.message))
        }
    }

    //actions 用户退出登录
    const userLogout = async () => {
        userInfo.value = { name: '', token: '' }
        wxSuccess.value = false
        REMOVE_USERINFO()
    }

    //actions 查询微信扫码接口（查看本地是否存储了数据）
    const queryState = () => {
        let timer: number = window.setInterval(() => {
            if (GET_USERINFO()) {
                visible.value = false
                wxSuccess.value = true
                userInfo.value = JSON.parse(GET_USERINFO() || '{}')
                clearInterval(timer)
            }
        }, 1000)
    }

    // states 登录框显隐控制数据
    const visible = ref<boolean>(false)

    // states 微信登录是否成功
    const wxSuccess = ref<boolean>(false)

    // states 用户获取的验证码
    const code = ref<string>('')

    // states 用户登录xx
    const userInfo = ref<UserInfo>(JSON.parse(GET_USERINFO() || '{}'))

    return { showLogin, closeLogin, getCode, userLogin, userLogout, queryState, visible, code, userInfo, wxSuccess }
})